package com.lmk.ms.common.utils;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Hashtable;

/**
 * 二维码图片工具类
 *
 * @author laomake@hotmail.com
 * @version 1.0
 * @date 2022/02/26
 */
public class QrCodeUtils {
    /**
     * 默认的图片格式
     */
    private static final String FORMAT_NAME = "PNG";

    /**
     * 二维码长宽尺寸
     */
    private static final int QRCODE_SIZE = 280;

    /**
     * Logo长宽尺寸
     */
    private static final int LOGO_SIZE = 60;

    /**
     * 文本格式的图片前缀
     */
    private static final String BASE64TOKEN = "base64,";

    /**
     * 默认字符集
     */
    private static final String DEFAULT_CHARSET = "UTF-8";

    /**
     * 生成二维码 无Logo
     *
     * @param content
     * @return
     * @throws Exception
     */
    public static String encode(String content) {
        BufferedImage image = createImage(content, null, false, false);
        return getImageText(image);
    }

    /**
     * 生成二维码，插入本地图片Logo
     *
     * @param content  编码内容
     * @param logoPath 要插入的图片地址
     * @param compress 是否压缩图片
     * @return
     * @throws Exception
     */
    public static String encodeFileLogo(String content, String logoPath, Boolean compress) {
        BufferedImage image = createImage(content, logoPath, true, compress);
        return getImageText(image);
    }

    /**
     * 生成二维码，插入网络图片Logo
     *
     * @param content
     * @param logoUrl
     * @param compress
     * @return
     * @throws Exception
     */
    public static String encodeNetLogo(String content, String logoUrl, Boolean compress) {
        BufferedImage image = createImage(content, logoUrl, false, compress);
        return getImageText(image);
    }

    /**
     * 生成二维码并输出到输出流
     *
     * @param content
     * @param os
     * @throws Exception
     */
    public static void encode(String content, OutputStream os) throws IOException {
        BufferedImage image = createImage(content, null, false, false);
        ImageIO.write(image, FORMAT_NAME, os);
    }

    /**
     * 生成二维码，输出到输出流，插入网络图片Logo
     *
     * @param content      编码内容
     * @param logoPath     要插入的图片地址
     * @param outputStream 图片输出流
     * @param compress     是否压缩图片
     * @throws Exception
     */
    public static void encodeNetLogo(String content, String logoPath, OutputStream outputStream, Boolean compress) throws IOException {
        BufferedImage image = createImage(content, logoPath, false, compress);
        ImageIO.write(image, FORMAT_NAME, outputStream);
    }

    /**
     * 生成二维码，输出到输出流，插入本地图片Logo
     *
     * @param content
     * @param logoPath
     * @param outputStream
     * @param compress
     * @throws Exception
     */
    public static void encodeLocalLogo(String content, String logoPath, OutputStream outputStream, Boolean compress) throws IOException {
        BufferedImage image = createImage(content, logoPath, true, compress);
        ImageIO.write(image, FORMAT_NAME, outputStream);
    }

    /**
     * 解析二维码
     *
     * @param qrCodeImagePath 二维码图片地址
     * @return
     * @throws Exception
     */
    public static String decode(String qrCodeImagePath) {
        String resultString = null;
        try {
            BufferedImage qrCodeImage = readImage(new File(qrCodeImagePath).toURI());
            if (qrCodeImage != null) {
                // 将图像数据转换为1 bit data
                LuminanceSource source = new BufferedImageLuminanceSource(qrCodeImage);
                BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

                Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
                hints.put(DecodeHintType.CHARACTER_SET, DEFAULT_CHARSET);

                Result result = new MultiFormatReader().decode(bitmap, hints);

                resultString = result.getText();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotFoundException e) {
            e.printStackTrace();
        }

        return resultString;
    }

    /**
     * 封装图片
     *
     * @param content
     * @param logoPath
     * @param compress
     * @return
     * @throws Exception
     */
    private static BufferedImage createImage(String content, String logoPath, Boolean localImage, Boolean compress) {
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, DEFAULT_CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);

        BitMatrix bitMatrix = null;
        try {
            bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        if (bitMatrix == null) {
            return null;
        }

        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();

        BufferedImage qrCodeImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                qrCodeImage.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        if (StringUtils.isBlank(logoPath)) {
            return qrCodeImage;
        }

        // 插入图片
        insertImage(qrCodeImage, logoPath, localImage, compress);

        return qrCodeImage;
    }

    /**
     * 插入LOGO
     *
     * @param erCodeImage
     * @param logoPath
     * @param compress
     * @throws Exception
     */
    private static void insertImage(BufferedImage erCodeImage, String logoPath, Boolean localLogoImage, Boolean compress) {
        Image logoImage = null;
        try {
            if (localLogoImage) {
                logoImage = readImage(new File(logoPath).toURI());
            } else {
                logoImage = readImage(new URL(logoPath).toURI());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

        if (logoImage == null) {
            return;
        }

        int width = logoImage.getWidth(null);
        int height = logoImage.getHeight(null);

        if (compress) { // 压缩LOGO
            if (width > LOGO_SIZE) {
                width = LOGO_SIZE;
            }
            if (height > LOGO_SIZE) {
                height = LOGO_SIZE;
            }
            Image scaleImage = logoImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            g.drawImage(scaleImage, 0, 0, null); // 绘制缩小后的图
            g.dispose();

            logoImage = scaleImage;
        }

        // 插入LOGO
        Graphics2D graph = erCodeImage.createGraphics();
        int x = (QRCODE_SIZE - width) / 2;
        int y = (QRCODE_SIZE - height) / 2;
        graph.drawImage(logoImage, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 10, 10);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }

    /**
     * 读取图片
     *
     * @param uri
     * @return
     * @throws IOException
     */
    private static BufferedImage readImage(URI uri) throws IOException {
        if ("data".equals(uri.getScheme())) {
            return readDataURIImage(uri);
        }
        BufferedImage result;
        try {
            result = ImageIO.read(uri.toURL());
        } catch (IllegalArgumentException iae) {
            throw new IOException("Resource not found: " + uri, iae);
        }
        if (result == null) {
            throw new IOException("Could not load " + uri);
        }
        return result;
    }

    /**
     * 读取图片
     *
     * @param uri
     * @return
     * @throws IOException
     */
    private static BufferedImage readDataURIImage(URI uri) throws IOException {
        String uriString = uri.toString();
        if (!uriString.startsWith("data:image/")) {
            throw new IOException("Unsupported data URI MIME type");
        }
        int base64Start = uriString.indexOf(BASE64TOKEN);
        if (base64Start < 0) {
            throw new IOException("Unsupported data URI encoding");
        }
        String base64DataEncoded = uriString.substring(base64Start + BASE64TOKEN.length());
        String base64Data = URLDecoder.decode(base64DataEncoded, "UTF-8");
        byte[] imageBytes = Base64.decodeBase64(base64Data);
        return ImageIO.read(new ByteArrayInputStream(imageBytes));
    }

    /**
     * 将图片转为Base64文字
     *
     * @param image
     * @return
     */
    private static String getImageText(RenderedImage image) {
        String text = null;
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            ImageIO.write(image, "png", baos);
            text = Base64.encodeBase64String(baos.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "data:image/png;base64," + text;
    }
}
